<template>
    <div class="basic-info-page">
        <UserSteps :currentStep="0" />
        <!-- 表格标题 -->
        <div class="table-title">基础信息收集</div>

        <!-- 基础信息表格 -->
        <div class="basic-info-table">
            <table>
                <tr>
                    <td colspan="2" class="label-cell">公司全称（必填）</td>
                    <td colspan="2" class="input-cell">
                        <van-field v-model="form.companyName" placeholder="请输入公司全称"
                            :rules="[{ required: true, message: '请输入公司全称' }]" style="width: 100%; padding: 8px;" />
                    </td>
                </tr>

                <tr>
                    <td colspan="2" class="label-cell">企业总人数（必填）</td>
                    <td colspan="2" class="input-cell">
                        <van-field v-model="form.totalEmployees" type="number" placeholder="请输入企业总人数"
                            :rules="[{ required: true, message: '请输入企业总人数' }]" style="width: 100%; padding: 8px;" />
                    </td>
                </tr>

                <tr>
                    <td class="label-cell">高层管理人数</td>
                    <td class="input-cell">
                        <van-field v-model="form.middleManagers" type="number" placeholder="请输入高层管理人员数"
                            :rules="[{ required: true, message: '请输入高层管理人员数' }]" style="width: 100%; padding: 8px;" />
                    </td>
                    <td class="label-cell">中层管理人数</td>
                    <td class="input-cell">
                        <van-field v-model="form.grassrootsManagers" type="number" placeholder="请输入中层管理人员数"
                            :rules="[{ required: true, message: '请输入中层管理人员数' }]" style="width: 100%; padding: 8px;" />
                    </td>
                </tr>

                <tr>
                    <td class="label-cell">基层干部人数</td>
                    <td class="input-cell">
                        <van-field v-model="form.frontlineEmployees" type="number" placeholder="请输入基层干部人数"
                            :rules="[{ required: true, message: '请输入基层干部人数' }]" style="width: 100%; padding: 8px;" />
                    </td>
                    <td class="label-cell">一线人数</td>
                    <td class="input-cell">
                        <van-field v-model="form.oneLineEmployees" type="number" placeholder="请输入一线员工人员"
                            :rules="[{ required: true, message: '请输入一线员工人员' }]" style="width: 100%; padding: 8px;" />
                    </td>
                </tr>

                <tr>
                    <td colspan="2" class="label-cell">主营业务（必填）</td>
                    <td colspan="2" class="input-cell">
                        <van-field v-model="form.mainBusiness" placeholder="请输入主营业务"
                            :rules="[{ required: true, message: '请输入主营业务' }]" style="width: 100%; padding: 8px;" />
                    </td>
                </tr>

                <tr>
                    <td colspan="2" class="label-cell">上一年度营收</td>
                    <td colspan="2" class="input-cell">
                        <van-field v-model="form.lastYearRevenue" type="number" placeholder="请输入上一年度营收（万元）"
                            style="width: 100%; padding: 8px;" />
                    </td>
                </tr>
            </table>
        </div>
        <!-- 信息提示 -->
        <div class="info-disclaimer">
            <p>本次收集的所有信息（包括但不限于文字、图像、数据）仅用于本次诊断分析之用。</p>
            <p>我们承诺将严格保密，未经您的明确授权，不会向任何第三方披露您的任何信息。</p>
        </div>
        <!-- 提交按钮 -->
        <div class="form-actions">
            <van-button round block type="primary" native-type="submit" @click="onSubmit()">
                提交
            </van-button>
        </div>
    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive } from 'vue'
import { showToast } from 'vant'
import { updateUser } from '../api/user'
import { addEnterprise, getEnterpriseById, updateEnterprise } from '../api/enterprise'
import UserSteps from '../components/UserSteps.vue'
// 定义表单数据结构
const form = reactive({
    companyName: '',           // 公司全称
    totalEmployees: '',        // 企业总人数
    middleManagers: '',        // 高层管理人员数
    grassrootsManagers: '',    // 中层管理人员数
    frontlineEmployees: '',    // 基层干部人数
    oneLineEmployees: '',        // 一线人员人数
    lastYearRevenue: '',       // 上一年度营收
    mainBusiness: ''           // 主营业务
})

// 表单校验函数
const validateForm = () => {
    // 验证必填字段
    if (!form.companyName) {
        showToast('请输入公司全称')
        return false
    }
    if (!form.totalEmployees) {
        showToast('请输入企业总人数')
        return false
    }
    if (!form.middleManagers) {
        showToast('请输入高层管理人员数')
        return false
    }
    if (!form.grassrootsManagers) {
        showToast('请输入中层管理人员数')
        return false
    }
    if (!form.frontlineEmployees) {
        showToast('请输入基层干部人数')
        return false
    }
    if (!form.mainBusiness) {
        showToast('请输入主营业务')
        return false
    }
    return true
}
//处理新增操作
const handleAdd = async (user: any) => {
    // 1.生成随机数作为企业id
    const enterpriseId = Math.floor(Math.random() * 1000000000)
    user.enterpriseId = enterpriseId
    //触发更新函数
    await updateUser(user).then(
        res => {
            console.log("更新成功", res)
        }
    ).catch(err => {
        console.log("更新失败", err)
    })
    //2.定义企业基础
    const enterprise = {
        "id": enterpriseId,
        "fullName": form.companyName,
        "totalCount": form.totalEmployees,
        "hightCount": form.middleManagers,
        "midCount": form.grassrootsManagers,
        "baseCount": form.frontlineEmployees,
        "frontCount": form.oneLineEmployees,
        "business": form.mainBusiness,
        "lastRevenue": form.lastYearRevenue,
        "version": 0,
        "createAt": "",
        "updateAt": "",
        "orgJson": "",
        "currentMenber": ""
    }
    //执行新增操作
    await addEnterprise(enterprise).then(
        res => {
            console.log("新增成功", res)
        }
    ).catch(err => {
        console.log("新增失败", err)
    })

}

// 处理更新操作
const handleUpdate = async (enterpriseId: any) => {
    const response: any = await getEnterpriseById(enterpriseId).catch(err => {
        console.log("获取失败", err)
    })
    const enterprise = response.data
    if (enterprise) {
        // 1.更新基础信息
        console.log("获取成功", enterprise)
        enterprise.fullName = form.companyName
        enterprise.totalCount = form.totalEmployees
        enterprise.hightCount = form.middleManagers
        enterprise.midCount = form.grassrootsManagers
        enterprise.baseCount = form.frontlineEmployees
        enterprise.frontCount = form.oneLineEmployees
    }
    await updateEnterprise(enterprise).then(
        res => {
            console.log("更新成功", res)
        }
    ).catch(err => {
        console.log("更新失败", err)
    })

}


//处理信息
const handleInfo = async () => {
    let user = JSON.parse(localStorage.getItem('user')!)
    if (!user.enterpriseId) {
        // 没有企业信息，执行新增操作
        await handleAdd(user)
    } else {
        // 有企业信息，执行更新操作
        await handleUpdate(user.enterpriseId)
    }
}
// 表单提交处理
const onSubmit = async () => {
    // 执行表单校验
    if (!validateForm()) {
        return
    }
    await handleInfo()
    // 处理表单提交逻辑
    console.log('提交的基础信息:', form)
    showToast('信息提交成功')
}

/**
 * 根据关联企业id，进行表单填充
 */
const fillForm = async (id: any) => {
    const response: any = await getEnterpriseById(id).catch(err => {
        console.log("获取失败", err);
    });
    console.log("获取的响应数据", response);
    if (response && response.data && response.code === 200) {
        const data = response.data; // 实际企业信息
        console.log("获取成功", data);

        // 填充表单
        form.companyName = data.fullName;
        form.totalEmployees = data.totalCount;
        form.middleManagers = data.hightCount;
        form.grassrootsManagers = data.midCount;
        form.frontlineEmployees = data.baseCount;
        form.oneLineEmployees = data.frontCount;
        form.mainBusiness = data.business;
        form.lastYearRevenue = data.lastRevenue;
    }
};

onMounted(async () => {
    // 获取用户信息
    let user = JSON.parse(localStorage.getItem('user')!)
    await fillForm(user.enterpriseId)
})


</script>

<style scoped>
.basic-info-page {
    padding: 10px;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    font-size: 16px;
}

.info-disclaimer {
    background-color: #f5f5f5;
    border: 1px solid #ddd;
    padding: 15px;
    margin-bottom: 15px;
    text-align: center;
    font-size: 14px;
    line-height: 1.5;
}

.table-title {
    text-align: center;
    font-weight: bold;
    background-color: #e0e0e0;
    padding: 10px;
    margin-bottom: 10px;
    font-size: 16px;
}

.basic-info-table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 20px;
}

.basic-info-table table {
    width: 100%;
    border-collapse: collapse;
}

.basic-info-table th,
.basic-info-table td {
    border: 1px solid #ccc;
    padding: 10px;
    text-align: left;
}

.label-cell {
    background-color: #f0f0f0;
    font-weight: bold;
    width: 96px;
}

.input-cell {
    padding: 0;
}

.form-actions {
    margin-top: 30px;
    padding: 0 15px;
}
</style>